package com.meteor.downloader.videodownloader.utils.dialog

import android.content.Context
import android.os.Bundle
import android.view.Gravity
import androidx.appcompat.app.AppCompatDialog
import com.meteor.downloader.videodownloader.R
import com.meteor.downloader.videodownloader.databinding.DialogRenameFileMdmBinding
import com.meteor.downloader.videodownloader.showToastIDMdm
import com.meteor.downloader.videodownloader.utils.MdmTotalUtils
import java.io.File

class DialogRenameFileMdm(
    private val mContext: Context,
    private val mRenameFile: File,
    private val newFileMdm: (File) -> Unit
) : AppCompatDialog(mContext) {
    private lateinit var mMdmBinding: DialogRenameFileMdmBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mMdmBinding = DialogRenameFileMdmBinding.inflate(layoutInflater)
        setContentView(mMdmBinding.root)
        setCancelable(true)

        mMdmBinding.etFileName.setText(mRenameFile.name)
        mMdmBinding.ivMdmCls.setOnClickListener {
            mMdmBinding.etFileName.text = null
        }
        mMdmBinding.tvCancel.setOnClickListener { dismiss() }
        mMdmBinding.tvYes.setOnClickListener {
            var newName = mMdmBinding.etFileName.text.toString().trim()
            if (newName.isEmpty()) {
                mContext.showToastIDMdm(R.string.mdm_no_file_name)
                return@setOnClickListener
            }
            if (mRenameFile.name == newName) {
                dismiss()
                return@setOnClickListener
            }
            if (!MdmTotalUtils.fileNameMdm(newName) && !MdmTotalUtils.fileNameMdm2(newName)) {
                mContext.showToastIDMdm(R.string.mdm_containts_unspor)
                return@setOnClickListener
            }
            if (!newName.contains(".")) {
                val ex = mRenameFile.extension
                if (!newName.endsWith(ex, true)) {
                    newName = "$newName.${ex}"
                }
            }
            val file = File(mRenameFile.parent, newName)
            if (file.exists()) {
                mContext.showToastIDMdm(R.string.mdm_file_name_exists)
            } else {
                newFileMdm(file)
                dismiss()
            }
        }

        DialogMangerMdmUtils.changeWindowHalf(window, 1.0f, Gravity.BOTTOM)
    }
}